package com.erclab.internal.xpresso.webapp.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.webapp.WebObjectFactory;

/**
 * @version 	1.0
 * @author
 */
public class ReportConstructor extends HttpServlet {

	private static final long serialVersionUID = 8256134712679966061L;
	protected static final Logger log = Logger.getLogger(ReportConstructor.class);
	
	public void init() throws ServletException {
		log.info("ReportConstructor servlet initializing.");
		super.init();
		log.info("ReportConstructor servlet initialized successfully.");
	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException, SecurityException {
			
			String viewHandler = null;
			String reportName = null;
			try {
				reportName = extractReportName(request.getServletPath());
				viewHandler = WebObjectFactory.createAndAddReport(request, reportName);
			} catch (SecurityException e) {
				log.error("A security exception was raised whe loading report: " + reportName);
				throw new SecurityException(e.getMessage());
			} catch (Exception e) {
				// TODO log4j
				throw new ServletException(e);
			}
			
			RequestDispatcher view = request.getRequestDispatcher(viewHandler);
			view.forward(request, response);
	}


	/**
	 * @param string
	 * @return
	 */
	protected String extractReportName(String path) {
		return path.substring(path.lastIndexOf('/') + 1, 
				path.indexOf(Settings.getProperty("application.reports.extension")));
	}

}
